package com.jframe.sso.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;

import com.jframe.cfg.model.Rolemenu;
import com.jframe.cfg.model.Sysmenu;
import com.jframe.cfg.service.RolemenuService;
import com.jframe.cfg.service.SysmenuService;
import com.jframe.sso.model.CurUser;
import com.jframe.sso.model.LoginLogs;
import com.jframe.sso.model.Role;
import com.jframe.sso.model.User;
import com.jframe.sso.service.LoginLogService;
import com.jframe.sso.service.RoleService;
import com.jframe.sso.service.UserService;
import com.jframe.sys.controller.utils.BaseAction;
import com.jframe.sys.utils.CalendarUtil;
import com.jframe.sys.utils.JsonUtil;
import com.jframe.sys.utils.PropertiesUtil;
import com.jframe.sys.utils.SpringUtil;
import com.jframe.sys.utils.StringUtil;
import com.jframe.sys.webui.Accrodion;
import com.jframe.sys.webui.Tree;

public class LoginAction extends BaseAction {

	public void login(){
		Map<String, String> map = new HashMap<String, String>();
		String userNo = this.request.getParameter("user");
		String pwd = this.request.getParameter("password");
		UserService userService = (UserService)SpringUtil.getBean("userService");		
		User user = userService.login(userNo, StringUtil.encrypt(pwd));		
		CurUser curUser = this.getCurUser();
		if(curUser==null||!curUser.getUserNo().equals(userNo)){
			curUser=new CurUser();
			curUser.setUserNo(userNo);
			curUser.setIp(this.getIpAddr());
			curUser.setLoginTime(CalendarUtil.getDateTime());
			if(user.getId()>0 && user.getActive()==1){
				if(this.getCurUser()!=null){
					LoginLogService loginLogService = (LoginLogService)SpringUtil.getBean("loginLogService");
					LoginLogs loginLogs = loginLogService.load("sessionId", this.getCurUser().getSessionId());
					loginLogs.setLoginOutTime(CalendarUtil.getDateTime());
					loginLogService.save(loginLogs);
				}
				curUser.setSessionId(session.getId());
				curUser.setUserId(user.getId());			
				curUser.setUserName(user.getUserName());
				curUser.setRoleId(user.getRoleId());		
				curUser.setDeptId(user.getDeptId());
				curUser.setMemberId(user.getMemberId());
				curUser.setSkin(user.getSkin());
				curUser.setRoleName(user.getRoleName());
				curUser.setEmail(user.getEmail());
				curUser.setTel(user.getTel());
				session.setAttribute("curUser", curUser);
				map.put("result", "true");				
			}else if(user.getId()>0&&user.getActive()!=1){
				map.put("result", "您的账号还未开通，请联系管理员");
			}else{
				map.put("result", "您输入的账号或者密码有误");
			}
			initLoginLogs(curUser);
		}else{
			map.put("result", "true");
		}		
		this.print(JsonUtil.map2Json(map));
	}
		
	public String dwrLogin(String args[]){
		Map<String, String> map = new HashMap<String, String>();
		String userNo = args[0];
		String pwd =args[1];
		String verifyCode = args[2];		
		if(verifyCode.equals(this.session.getAttribute("VerifyCode"))){
			CurUser curUser = this.getCurUser();
			if(curUser==null||!curUser.getUserNo().equals(userNo)){
				curUser = new CurUser();			
				curUser.setUserNo(userNo);
				curUser.setIp(this.getIpAddr());
				curUser.setLoginTime(CalendarUtil.getDateTime());				
				UserService userService = (UserService)SpringUtil.getBean("userService");
				User user = userService.login(userNo, StringUtil.encrypt(pwd));		
				if(user.getId()>0 && user.getActive()==1){
					if(this.getCurUser()!=null){
						LoginLogService loginLogService = (LoginLogService)SpringUtil.getBean("loginLogService");
						LoginLogs loginLogs = loginLogService.load("sessionId", this.getCurUser().getSessionId());
						loginLogs.setLoginOutTime(CalendarUtil.getDateTime());
						loginLogService.save(loginLogs);
					}
					curUser.setSessionId(session.getId());
					curUser.setUserId(user.getId());
					curUser.setUserName(user.getUserName());
					curUser.setRoleId(user.getRoleId());
					curUser.setDeptId(user.getDeptId());
					curUser.setMemberId(user.getMemberId());
					curUser.setSkin(user.getSkin());
					session.setAttribute("curUser", curUser);
					map.put("result", "true");
				}else if(user.getId()>0&&user.getActive()!=1){
					map.put("result", "您的账号还未开通，请联系管理员");
				}else{
					map.put("result", "您输入的账号或者密码有误");
				}
				initLoginLogs(curUser);
			}else{
				map.put("result", "true");
			}
		}else{
			map.put("result", "验证码错误");
		}		
		return JsonUtil.map2Json(map);
	}
	
	public void loginOut(){
		PropertiesUtil prop = PropertiesUtil.getInstance(StringUtil.getPrjAbsolutePath()+ "WEB-INF/classes/sys-config.properties");
		try{
			session.invalidate();
			this.sendRedirect(this.request.getContextPath()+"/"+prop.getKeyValue("loginOutUrl"));
		}catch(Exception e){
			this.sendRedirect(this.request.getContextPath()+"/"+prop.getKeyValue("loginOutUrl"));
		}
	}
	
	public void getAccrodions(){
		RoleService roleService = (RoleService)this.getBean("roleService");
		SysmenuService sysmenuService = (SysmenuService)SpringUtil.getBean("sysmenuService");
		RolemenuService rolemenuService = (RolemenuService)this.getBean("rolemenuService");
		CurUser user = this.getCurUser();
		Role role = roleService.load(user.getRoleId());
		Rolemenu rolemenu = rolemenuService.load("roleId",role.getId());
		
		String[] menuIds = rolemenu.getMenuIds().split(",");
		List<Sysmenu> topls = sysmenuService.findTopSysmenu();
		List<Accrodion> ls = new ArrayList<Accrodion>();
		for(Sysmenu menu:topls){
			boolean flag = false;
			for(String menuId:menuIds ){
				if(menuId.equals(""+menu.getId())){
					flag=true;
				}
			}
			if(flag){
				Accrodion accrodion = new Accrodion();
				accrodion.setId(""+menu.getId());
				accrodion.setTitle(menu.getText());
				accrodion.setIconCls(menu.getIconCls());
				ls.add(accrodion);
			}
		}
		this.print(JsonUtil.list2Json(ls));
	}
	
	public void getTrees() throws UnsupportedEncodingException{
		SysmenuService sysmenuService = (SysmenuService)SpringUtil.getBean("sysmenuService");
		RoleService roleService = (RoleService)this.getBean("roleService");
		RolemenuService rolemenuService = (RolemenuService)this.getBean("rolemenuService");
		int id = StringUtil.parseInt(this.request.getParameter("id"));	
		String title=StringUtil.null2Space(this.request.getParameter("title"));
		Role role = roleService.load(this.getCurUser().getRoleId());
		if(id<1){
			String temp = new String(title.getBytes("ISO-8859-1"),"utf-8");  
			title = URLDecoder.decode(temp, "utf-8");
			Sysmenu sysmenu = sysmenuService.getTopSysmenuByTitleAndGroup(title,role.getGroupId());
			id=sysmenu.getId();
		}
		List<Sysmenu> treels = sysmenuService.findListByUpId(id);		
		Rolemenu rolemenu = rolemenuService.load("roleId",role.getId());
		String[] menuIds = rolemenu.getMenuIds().split(",");		
		List<Tree> ls = new ArrayList<Tree>();
		for(Sysmenu menu:treels){
			boolean flag = false; //权限标志
			for(String menuId:menuIds ){
				if(menuId.equals(""+menu.getId())){
					flag=true;
					break;
				}
			}
			if(flag==true){
				Tree tree = new Tree();
				tree.setId(""+menu.getId());
				tree.setIconCls(menu.getIconCls());
				tree.setText(menu.getText());
				if(menu.getLeaf()==0){
					tree.setState("closed");	
				}
				ls.add(tree);
			}
		}
		this.print(JsonUtil.list2Json(ls));
	}
	
	private void initLoginLogs(CurUser curUser){
		LoginLogService loginLogService = (LoginLogService)SpringUtil.getBean("loginLogService");
		LoginLogs loginLogs = new LoginLogs();
		loginLogs.setUserNo(curUser.getUserNo());
		loginLogs.setLoginTime(curUser.getLoginTime());
		loginLogs.setIp(curUser.getIp());
		loginLogs.setSessionId(this.session.getId());
		if(curUser.getUserId()==0){
			loginLogs.setUserName("登陆失败用户");
			loginLogs.setIsLogin("2");
		}else{
			loginLogs.setUserId(curUser.getUserId());
			loginLogs.setUserName(curUser.getUserName());
			loginLogs.setDeptId(curUser.getDeptId());
			loginLogs.setIsLogin("1");
			loginLogs.setRoleId(curUser.getRoleId());
		}
		loginLogService.save(loginLogs);
	}
	
	public void getUrl(){
		Map<String, String> map = new HashMap<String, String>();
		SysmenuService sysmenuService = (SysmenuService)SpringUtil.getBean("sysmenuService");
		int id = StringUtil.parseInt(this.request.getParameter("id"));
		Sysmenu menu = sysmenuService.load(id);
		map.put("url",menu.getUrl());
		map.put("title", menu.getText());
		map.put("iconCls", menu.getIconCls());
		this.print(JsonUtil.map2Json(map));
	}
	
	public void getVerifyCode(){		
		//设置页面不缓存
		response.setHeader ("Cache-Control", "no-store") ;
		response.setHeader ("Pragma", "no-cache") ;
		response.setDateHeader ("Expires", 0) ;
		// 在内存中创建图象
		int width = 60, height = 20 ;
		BufferedImage image = new BufferedImage (width, height,BufferedImage.TYPE_INT_RGB) ;
		// 获取图形上下文
		Graphics g = image.getGraphics () ;
		//生成随机类
		Random random = new Random () ;
		// 设定背景色
		g.setColor (getRandColor (200, 250)) ;
		g.fillRect (0, 0, width, height) ;
		//设定字体
		g.setFont (new Font ("宋体", Font.BOLD, 18)) ;
		// 随机产生155条干扰线，使图象中的认证码不易被其它程序探测到
		g.setColor (getRandColor (160, 200)) ;
		for (int i = 0 ; i < 155 ; i++)
		{
			int x = random.nextInt (width) ;
			int y = random.nextInt (height) ;
			int xl = random.nextInt (12) ;
			int yl = random.nextInt (12) ;
			g.drawLine (x, y, x + xl, y + yl) ;
		}
		// 取随机产生的认证码(4位数字)
		String sRand = "" ;
		for (int i = 0 ; i < 4 ; i++)
		{
			String rand = String.valueOf (random.nextInt (10)) ;
			sRand += rand ;
			// 将认证码显示到图象中
			g.setColor (new Color (20 + random.nextInt (110),
								   20 + random.nextInt (110),
								   20 + random.nextInt (110))) ; //调用函数出来的颜色相同，可能是因为种子太接近，所以只能直接生成
			g.drawString (rand, 13 * i + 6, 16) ;
		}
		// 将认证码存入SESSION
		HttpSession session = request.getSession () ;
		session.setAttribute ("VerifyCode", sRand) ;
		// 图象生效
		g.dispose () ;
		// 输出图象到页面
		try {
			ImageIO.write (image, "JPEG", response.getOutputStream ()) ;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private Color getRandColor (int fc, int bc)
	{
		//给定范围获得随机颜色
		Random random = new Random () ;
		if (fc > 255) fc = 255 ;
		if (bc > 255) bc = 255 ;
		int r = fc + random.nextInt (bc - fc) ;
		int g = fc + random.nextInt (bc - fc) ;
		int b = fc + random.nextInt (bc - fc) ;
		return new Color (r, g, b) ;
	}

}
